package Program.Tool;


import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.JdbcUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DruidJDBC {
    //连接池对象
    private static DataSource dataSource;

    static{
        try {
            //1、提供静态代码块，来加载配置文件，初始化连接池对象
            Properties prop = new Properties();
            InputStream is =  is = JdbcUtils.class.getClassLoader().getResourceAsStream("Druidconfig\\druid.properties");
            prop.load(is);
            //2、获取数据库连接池
            try {
                //获取连接池对象
                dataSource = DruidDataSourceFactory.createDataSource(prop);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取连接池对象
    public static DataSource getDataSource() {
        return dataSource;

    }
    //获取执行数据库的连接连接的方法
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    //释放资源
    public static void close(PreparedStatement stat, Connection conn){
        if (stat!=null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //释放资源  dql  查询时(重载)
    public static void close(ResultSet rs, PreparedStatement stat, Connection conn){
        close(stat,conn);
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
